import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/home/home.vue'
import Login from '@/views/login'
import Storage from '@/Storage'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      // 首页
      path: '/',
      name: 'home',
      component: Home,
      redirect: 'index',
      children: [
        {
          // 首页
          path: 'index',
          name: 'Index',
          component: () => import('../views/home/index.vue')
        },
        {
          // 商品页
          path: 'product/:id',
          name: 'Product',
          component: () => import('../views/home/product.vue')
        },
        {
          path: 'dettail/:id',
          name: 'Dettail',
          component: () => import('../views/home/dettail.vue')
        }
      ]
    },
    {
      // 购物车
      path: '/cart',
      name: 'Cart',
      component: () => import('../views/cart')
    },
    {
      // 订单路由
      path: '/order',
      name: 'Order',
      component: () => import('../views/order')
    },
    {
      // 订单支付页
      path: '/orderpay/:id',
      name: 'OrderPay',
      component: () => import('../views/order/orderPay.vue')
    },
    {
      // 订单提交页
      path: '/orderconfirm',
      name: 'OrderConfirm',
      component: () => import('../views/order/orderConfirm.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: Login

    },
    {
      // 订单详情页
      path: '/orderList',
      name: 'OrderList',
      component: () => import('../views/order/orderList.vue')
    }
  ]
})
router.beforeEach((to, from, next) => {
  const token = Storage.getItem('token')
  if (token) {
    if (to.path === '/login') {
      alert('不要重复登入')
      next(from.path)
    } else {
      next()
    }
  } else {
    if (to.path === '/cart' || to.path === '/orderconfirm' || to.path === '/orderList' || to.path === '/orderpay') {
      alert('请登入后访问')
      next('/login?history=' + to.path)
    } else {
      next()
    }
  }
})

export default router
